﻿define([
    'dojo/_base/declare',
    'dijit/_WidgetBase',
    'dijit/_TemplatedMixin',
    'dijit/_WidgetsInTemplateMixin',
    'dojo/store/Memory',
    'dojo/_base/lang',
    'dojo/_base/Color',
    'dojo/_base/array',

    'dojo/topic',
    'dojo/aspect',
    'dojo/dom-style',
    'dojo/dom-construct',
    'dojo/dom-class',
    'esri/toolbars/draw',
    'esri/graphic',
    'esri/layers/GraphicsLayer',
    'esri/renderers/SimpleRenderer',
    'esri/symbols/SimpleLineSymbol',
    'esri/symbols/SimpleFillSymbol',
    'esri/renderers/UniqueValueRenderer',
    'esri/layers/FeatureLayer',

    'dojo/i18n!./Measure/nls/resource',
    'dojo/text!./Measure/templates/Measure.html',

    'dijit/form/Button',

    'xstyle/css!./Measure/css/adw-icons.css',
    'xstyle/css!./Measure/css/Measure.css'
], function (declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Memory, lang, Color, array,
             topic, aspect, Style, domConstruct, domClass, Draw, Graphic, GraphicsLayer,
             SimpleRenderer, SimpleLineSymbol, SimpleFillSymbol, UniqueValueRenderer, FeatureLayer,
             i18n, MeasureTemplate) {

    // main growler dijit container
    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
        widgetsInTemplate: true,
        templateString: MeasureTemplate,
        i18n: i18n,
        drawToolbar: null,
        drawStatus: null,
        mapClickMode: null,
        pointArray: null,
        baseClass: 'gis_MeasureDijit',
        postCreate: function () {
            this.inherited(arguments);
            this.drawStatus = "";
            this.pointArray = [];
            this.drawToolbar = new Draw(this.map);
            this.map.on('click', lang.hitch(this, 'onMapClick'));
            this.drawToolbar.on('draw-end', lang.hitch(this, 'onDrawToolbarDrawEnd'));

            this.createGraphicLayers();
            this.own(topic.subscribe('mapClickMode/currentSet', lang.hitch(this, 'setMapClickMode')));
            topic.subscribe('measure/clear', lang.hitch(this, 'clearGraphics'));

        },
        createGraphicLayers: function () {
            this.polylineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 0, 0]), 2);
            this.polylineGraphics = new GraphicsLayer({
                id: 'measureGraphics_line',
                title: 'Draw Graphics'
            });
            this.polylineRenderer = new SimpleRenderer(this.polylineSymbol);
            this.polylineRenderer.label = 'User drawn lines';
            this.polylineRenderer.description = 'User drawn lines';
            this.polylineGraphics.setRenderer(this.polylineRenderer);
            this.map.addLayer(this.polylineGraphics);

            this.polygonSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 0, 0]), 2), new Color([0, 0, 0, 0.25]));

            this.polygonGraphics = new GraphicsLayer({
                id: 'measureGraphics_poly',
                title: 'Draw Graphics'
            });
            this.polygonRenderer = new SimpleRenderer(this.polygonSymbol);
            this.polygonRenderer.label = 'User drawn polygons';
            this.polygonRenderer.description = 'User drawn polygons';
            this.polygonGraphics.setRenderer(this.polygonRenderer);
            this.map.addLayer(this.polygonGraphics);
        },
        onMapClick: function (evt) {
            var xvalue = evt.mapPoint.x.toFixed(2);
            var yvalue = evt.mapPoint.y.toFixed(2);
            if (this.drawStatus === "MEASURE_DISTANCE" || this.drawStatus === "MEASURE_AREA") {
                this.pointArray.push({x: xvalue, y: yvalue});
                this.calculateResultUpdate();
            }
        },
        calculateResultUpdate: function () {
            if (this.drawStatus === "MEASURE_DISTANCE") {
                var ret = 0.00;
                for (var i = 0; i < this.pointArray.length - 1; i++) {
                    ret += Math.sqrt((this.pointArray[i].x - this.pointArray[i + 1].x) * (this.pointArray[i].x - this.pointArray[i + 1].x) + (this.pointArray[i].y - this.pointArray[i + 1].y) * (this.pointArray[i].y - this.pointArray[i + 1].y));
                }
                if (ret < 1000) {
                    ret = ret.toFixed(2);
                    this.measureResult.innerText = ret.toString() + " 米";
                }
                else {
                    ret = ret / 1000;
                    ret = ret.toFixed(2)
                    this.measureResult.innerText = ret.toString() + " 千米";
                }
            }
            else if (this.drawStatus === "MEASURE_AREA") {
                var ret = 0.00;
                for (var i = 0; i < this.pointArray.length; i++) {
                    if (i < this.pointArray.length - 1) {
                        ret += this.pointArray[i].x * this.pointArray[i + 1].y - this.pointArray[i + 1].x * this.pointArray[i].y;
                    }
                    else {
                        ret += this.pointArray[i].x * this.pointArray[0].y - this.pointArray[0].x * this.pointArray[i].y;
                    }
                }
                if (ret < 0) {
                    ret = ret * (-1);
                }
                ret = ret / 2.0;
                if (ret < 100000) {
                    ret = ret.toFixed(2);
                    this.measureResult.innerText = ret.toString() + " 平方米";
                }
                else {
                    ret = ret / 1000000;
                    ret = ret.toFixed(2)
                    this.measureResult.innerText = ret.toString() + " 平方千米";
                }
            }
        },
        onDrawToolbarDrawEnd: function (evt) {
            this.drawToolbar.deactivate();
            this.measureModeTextNode.innerText = this.i18n.labels.currentDrawModeNone;
            var graphic;
            this.pointArray = [];
            switch (evt.geometry.type) {
                case 'polygon':
                    graphic = new Graphic(evt.geometry, null, {
                        ren: 1
                    });
                    this.polygonGraphics.add(graphic);
                    for (var i = 0; i < evt.geometry.rings[0].length; i++) {
                        this.pointArray.push({x: evt.geometry.rings[0][0][0], y: evt.geometry.rings[0][0][1]});
                    }
                    break;
                case 'polyline':
                    graphic = new Graphic(evt.geometry);
                    this.polylineGraphics.add(graphic);
                    for (var i = 0; i < evt.geometry.paths[0].length; i++) {
                        this.pointArray.push({x: evt.geometry.paths[0][0][0], y: evt.geometry.paths[0][0][1]});
                    }
                    break;
                default:
            }
            this.connectMapClick();
        },

        measureByPolyline: function () {
            this.disconnectMapClick();
            this.drawToolbar.activate(Draw.POLYLINE);
            this.measureModeTextNode.innerText = "距离测量";
            this.drawStatus = "MEASURE_DISTANCE";
            this.measureResult.innerText = "";
            this.pointArray = [];
        },
        measureByPolygon: function () {
            this.disconnectMapClick();
            this.drawToolbar.activate(Draw.POLYGON);
            this.measureModeTextNode.innerText = "面积测量";
            this.drawStatus = "MEASURE_AREA";
            this.measureResult.innerText = "";
            this.pointArray = [];
        },
        disconnectMapClick: function () {
            this.clearGraphics();
            topic.publish('mapClickMode/setCurrent', 'measure');
            this.enableStopButtons();
        },
        connectMapClick: function () {
            // 恢复量测前的鼠标状态
            if ((dojo.hasClass(document.getElementById("panState"), "displayNone"))) {
                topic.publish('mapClickMode/currentSet', 'identify');
            }
            else {
                topic.publish('mapClickMode/setDefault');
            }

            this.measureModeTextNode.innerText = "无";

            this.drawStatus = "";
            this.pointArray = [];
            this.calculateResultUpdate();
            this.disableStopButtons();
        },
        clearGraphics: function () {
            this.endDrawing();
            this.connectMapClick();
            this.measureModeTextNode.innerText = '无';
            this.measureResult.innerText = "";
            this.pointArray = [];
        },
        stopDrawing: function () {
            this.drawToolbar.deactivate();
            this.measureModeTextNode.innerText = '无';
            this.connectMapClick();
            this.measureResult.innerText = "";
            this.pointArray = [];
        },
        endDrawing: function () {
            this.polylineGraphics.clear();
            this.polygonGraphics.clear();
            this.drawToolbar.deactivate();
            this.disableStopButtons();
        },
        disableStopButtons: function () {
            this.stopDrawingButton.set('disabled', true);
            this.eraseDrawingButton.set('disabled', !this.noGraphics());
        },
        enableStopButtons: function () {
            this.stopDrawingButton.set('disabled', false);
            this.eraseDrawingButton.set('disabled', !this.noGraphics());
        },
        noGraphics: function () {
            if (this.polylineGraphics.graphics.length > 0) {
                return true;
            } else if (this.polygonGraphics.graphics.length > 0) {
                return true;
            }
            else {
                return false;
            }
            return false;
        },
        setMapClickMode: function (mode) {
            this.mapClickMode = mode;
        }
    });
});